#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -f /etc/os-release ]; then
   echo "Linux system."
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   if [ -f ~/.bash_profile ]; then
      source ~/.bash_profile
    fi
elif command -v wmic >/dev/null 2>&1 || command -v cmd >/dev/null 2>&1; then
   echo "Windows system."
fi

APP_TARGET_DIR_NAME="ace-step"

echo "lmdprogress:3"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_conda.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo $CURRENT_APP_PATH
mkdir -p "$CURRENT_APP_PATH"

echo "lmdprogress:8"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

echo "lmdprogress:12"

export GIT_HOST=${GITHUB_PROXY}"https://github.com"
export GIT_REPO_URL=${GIT_HOST}/ace-step/ACE-Step
export GIT_REPO_BRANCH="main"
export LOCAL_REPO_PATH="$CURRENT_APP_PATH"
sh "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/git_clone_and_fetch.sh"

echo "lmdprogress:20"

cd "$CURRENT_APP_PATH"

# conda update -n base conda -y

echo "lmdprogress:23"

CONDA_PREFIX="./venv"

if [ -d "$CONDA_PREFIX" ]; then
    echo "found ./venv. remove it. "
    rm -rf "$CONDA_PREFIX"
fi

export PYTHON_VER_ENV=3.12
conda_create_env $CONDA_PREFIX python=$PYTHON_VER_ENV pip=25.2 -y


echo "lmdprogress:30"

cd "$CURRENT_APP_PATH"

echo "lmdprogress:40"

grep -vE '^torch' requirements.txt > requirements-temp.txt

conda_run_pip_install -r requirements-temp.txt

echo "lmdprogress:43"
if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_mac.sh"
elif command -v wmic >/dev/null 2>&1 || command -v cmd >/dev/null 2>&1; then
   source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_multi_method.sh"
   conda_run_pip_install triton-windows
fi

echo "lmdprogress:44"

conda_run_pip_install chardet devicetorch huggingface_hub hf_xet

echo "lmdprogress:50"
conda_run_pip_install -e .
echo "start download models"
echo "lmdprogress:65"
if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

export HF_HOME="$CURRENT_APP_PATH/checkpoints"
echo "set HF_HOME: $HF_HOME"

# If don't use symlink, add this --local-dir-use-symlinks False
# conda run -p $CONDA_PREFIX --no-capture-output hf download ACE-Step/ACE-Step-v1-3.5B
conda_run_hf_download ACE-Step/ACE-Step-v1-3.5B
conda_run_hf_download ACE-Step/ACE-Step-v1-chinese-rap-LoRA

echo "lmdprogress:100"


